package com.keensense.vcm.internal;

import org.apache.http.HttpStatus;

import com.keensense.vcm.ClientException;
import com.keensense.vcm.VCMErrorCode;
import com.keensense.vcm.VCMException;
import com.keensense.vcm.common.comm.ResponseHandler;
import com.keensense.vcm.common.comm.ResponseMessage;
import com.keensense.vcm.common.utils.ExceptionFactory;

/**
 * @author lanjian
 * @date 2020/4/29
 */
public class VCMErrorResponseHandler implements ResponseHandler {

    @Override
    public void handle(ResponseMessage response) throws VCMException, ClientException {
        if (response.isSuccessful()) {
            return;
        }
        String requestId = response.getRequestId();
        int statusCode = response.getStatusCode();
        if (response.getContent() == null) {
            /**
             * When HTTP response body is null, handle status code 404 Not Found, 304 Not Modified, 412 Precondition
             * Failed especially.
             */
            if (statusCode == HttpStatus.SC_NOT_FOUND) {
                throw ExceptionFactory.createVCMException(requestId, VCMErrorCode.SC_NOT_FOUND, "Not Found");
            } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                throw ExceptionFactory.createVCMException(requestId, VCMErrorCode.NOT_MODIFIED, "Not Modified");
            } else if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
                throw ExceptionFactory.createVCMException(requestId, VCMErrorCode.PRECONDITION_FAILED,
                    "Precondition Failed");
            } else {
                throw ExceptionFactory.createUnknownVCMException(requestId, statusCode);
            }
        }

    }

}